package com.tbynet.jwp.model;

import org.phprpc.util.AssocArray;
import org.phprpc.util.Cast;
import org.phprpc.util.PHPSerializer;

import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.tbynet.jwp.model.base.BaseUsermeta;

/**
 * 用户的元数据Model
 *
 * 核心职责：
 * 1. 用户元数据管理
 * 2. 会话令牌管理
 * 3. 权限和能力管理
 *
 * 设计原则：
 * - 继承JwpModel获得通用功能
 * - 专注于元数据特定的业务方法
 * - 提供便捷的序列化/反序列化方法
 *
 * @author 佰亿互联
 * @version 2.0
 * @since 2025-11-04
 */
@SuppressWarnings("serial")
public class Usermeta extends BaseUsermeta<Usermeta> {

    // ========== 元数据键常量 ==========

    public static final String role = "role"; //角色，自定义，区分能力capabilities
    public static final String permissions = "permissions"; //权限，自定义，区分能力

    public static final String nickname = "nickname"; //Adam
    public static final String first_name    = "first_name";    //
    public static final String last_name = "last_name"; //
    public static final String description = "description"; //
    public static final String rich_editing = "rich_editing"; //true
    public static final String syntax_highlighting = "syntax_highlighting"; //true
    public static final String comment_shortcuts = "comment_shortcuts"; //false
    public static final String admin_color = "admin_color"; //fresh
    public static final String use_ssl = "use_ssl"; //0
    public static final String show_admin_bar_front = "show_admin_bar_front";    //true
    public static final String locale = "locale"; //
    public static final String wp_capabilities = "wp_capabilities"; //能力
    public static final String wp_user_level = "wp_user_level"; //10
    public static final String dismissed_wp_pointers = "dismissed_wp_pointers"; //wp496_privacy,theme_editor_notice
    public static final String show_welcome_panel = "show_welcome_panel"; //1
    public static final String wp_dashboard_quick_press_last_post_id = ""; //6
    public static final String community_events_location = "community-events-location"; //a:1:{s:2:"ip";s:2:"::";}
    public static final String closedpostboxes_page = "closedpostboxes_page"; //a:0:{}
    public static final String metaboxhidden_page = "metaboxhidden_page"; //a:5:{i:0;s:10:"postcustom";i:1;s:16:"commentstatus...
    public static final String wp_user_settings = "wp_user-settings"; //editor=tinymce&mfold=o&libraryContent=browse&hidet...
    public static final String wp_user_settings_time = "wp_user-settings-time"; //1553349434
    public static final String managenav_menuscolumnshidden = "managenav-menuscolumnshidden"; //a:5:{i:0;s:11:"link-target";i:1;s:11:"css-classes"...
    public static final String metaboxhidden_nav_menus = "metaboxhidden_nav-menus"; //a:2:{i:0;s:12:"add-post_tag";i:1;s:15:"add-post_fo...
    public static final String nav_menu_recently_edited = "nav_menu_recently_edited"; //2
    public static final String wp_media_library_mode = "wp_media_library_mode"; //list
    public static final String session_tokens = "session_tokens"; //用户会话

    public static final String simple_local_avatar = "simple_local_avatar"; //用户头像

    // ========== 元数据设置方法 ==========

    public void setFirstName(String value) {
        setMetaKey(first_name);
        setMetaValue(value);
    }

    public void setLastName(String value) {
        setMetaKey(last_name);
        setMetaValue(value);
    }

    public void setNickname(String value) {
        setMetaKey(nickname);
        setMetaValue(value);
    }

    public void setDescription(String value) {
        setMetaKey(description);
        setMetaValue(value);
    }

    public void setLocale(String value) {
        setMetaKey(locale);
        setMetaValue(value);
    }

    public void setAdminColor(String value) {
        setMetaKey(admin_color);
        setMetaValue(value);
    }

    public void setRichEditing(String value) {
        setMetaKey(rich_editing);
        setMetaValue(value);
    }

    public void setSyntaxHighlighting(String value) {
        setMetaKey(syntax_highlighting);
        setMetaValue(value);
    }

    public void setCommentShortcuts(String value) {
        setMetaKey(comment_shortcuts);
        setMetaValue(value);
    }

    public void setShowAdminBarFront(String value) {
        setMetaKey(show_admin_bar_front);
        setMetaValue(value);
    }

    public void setUseSSL(String value) {
        setMetaKey(use_ssl);
        setMetaValue(value);
    }

    public void setWpUserLevel(String value) {
        setMetaKey(wp_user_level);
        setMetaValue(value);
    }

    public void setDismissedWpPointers(String value) {
        setMetaKey(dismissed_wp_pointers);
        setMetaValue(value);
    }

    public void setRole(String value) {
        setMetaKey(role);
        setMetaValue(value);
    }

    public void setSimpleLocalAvatar(String value) {
        setMetaKey(simple_local_avatar);
        setMetaValue(value);
    }

    // ========== 权限管理方法 ==========

    /**
     * 获取权限
     */
    public AssocArray getPermissions() throws Exception {
        if (StrKit.isBlank(getMetaValue())) {
            return new AssocArray();
        }
        return (AssocArray) unserializeFromPhp(getMetaValue());
    }

    /**
     * 设置权限
     */
    public void setPermissions(Object..._permissions) throws Exception {
        AssocArray array = new AssocArray();

        for(Object permission : _permissions) {
            Kv kv = (Kv) permission;
            for(Object key : kv.keySet()) {
                array.set(String.valueOf(key), kv.get(key));
            }
        }

        setMetaKey(permissions);
        setMetaValue(serializeToPhp(array));
    }

    /**
     * 删除权限
     */
    public void delPermissions(String permission) throws Exception {
        AssocArray array = getWpCapabilities();
        if(null != array && !array.isEmpty()) {
            array.remove(permission);
        }

        setMetaKey(permissions);
        setMetaValue(serializeToPhp(array));
    }

    /**
     * 获取WordPress能力
     */
    public AssocArray getWpCapabilities() throws Exception {
        if (StrKit.isBlank(getMetaValue())) {
            return new AssocArray();
        }
        return (AssocArray) unserializeFromPhp(getMetaValue());
    }

    /**
     * 设置WordPress能力
     */
    public void setWpCapabilities(Object...capabilities) throws Exception {
        AssocArray array = new AssocArray();

        for(Object capability : capabilities) {
            array.set(String.valueOf(capability), true);
        }

        setMetaKey(wp_capabilities);
        setMetaValue(serializeToPhp(array));
    }

    /**
     * 删除WordPress能力
     */
    public void delWpCapabilities(String capability) throws Exception {
        AssocArray array = getWpCapabilities();
        if(null != array && !array.isEmpty()) {
            array.remove(capability);
        }

        setMetaKey(wp_capabilities);
        setMetaValue(serializeToPhp(array));
    }

    // ========== 会话管理方法 ==========

    /**
     * 获取用户所有会话
     */
    public AssocArray getSessionTokens() throws Exception {
        if (StrKit.isBlank(getMetaValue())) {
            return new AssocArray();
        }
        return (AssocArray) unserializeFromPhp(getMetaValue());
    }

    /**
     * 获取指定会话
     */
    public Kv getSessionTokens(String sessionId) throws Exception {
        AssocArray array = getSessionTokens();
        if(null == array || array.isEmpty()) {
            return null;
        }

        Object object = array.toLinkedHashMap().get(sessionId);
        return (Kv) Cast.cast(object, Kv.class);
    }

    /**
     * 设置用户会话
     */
    public void setSessionTokens(String sessionId, long expiration, String ip, String ua, long login) throws Exception {
        Kv session = Kv.by("expiration", expiration).set("ip", ip).set("ua", ua).set("login", login);
        boolean exists = false;

        AssocArray array = getSessionTokens();
        if(null != array && !array.isEmpty()) {
            if(null != array.get(sessionId)) {
                array.set(sessionId, session);
                exists = true;
            }
        }

        if(false == exists) {
            array.set(sessionId, session);
        }

        setMetaKey(session_tokens);
        setMetaValue(serializeToPhp(array));
    }

    /**
     * 删除用户会话
     */
    public void delSessionTokens(String sessionId) throws Exception {
        AssocArray array = getSessionTokens();
        if(null != array && !array.isEmpty()) {
            array.remove(sessionId);
        }

        setMetaKey(session_tokens);
        setMetaValue(serializeToPhp(array));
    }

    // ========== 业务方法 ==========

    /**
     * 验证元数据基本信息
     */
    public boolean validateBasicInfo() {
        return validateRequired("user_id", "用户ID") &&
                validateRequired("meta_key", "元数据键") &&
                validateLength("meta_key", "元数据键", 1, 255);
    }

    /**
     * 检查是否为会话元数据
     */
    public boolean isSessionToken() {
        return session_tokens.equals(getMetaKey());
    }

    /**
     * 检查是否为权限元数据
     */
    public boolean isPermission() {
        return permissions.equals(getMetaKey());
    }

    /**
     * 转换为安全的数据Map（排除敏感信息）
     */
    public java.util.Map<String, Object> toSafeMap() {
        if (isSessionToken() || isPermission()) {
            return toMap("meta_value");
        }
        return toMap();
    }
}